package kr.ac.skhu.m.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestUtils;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

/**
 * Servlet implementation class Guestbook
 */
@WebServlet("/Guestbook")
public class Guestbook extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Guestbook() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		
		String mode = ServletRequestUtils.getStringParameter(request, "mode", "");
		int gb_page = ServletRequestUtils.getIntParameter(request, "gb_page", 1);
		
		
		//목록 URL
		String detailUrl = "http://m.web1234.woobi.co.kr/guest_book.php?gb_page=" + gb_page;
		
		if(mode.equalsIgnoreCase("i")){
			String writer = ServletRequestUtils.getStringParameter(request, "writer", "");
			String password = ServletRequestUtils.getStringParameter(request, "password", "");
			String c_txt = ServletRequestUtils.getStringParameter(request, "c_txt", "");
			c_txt = URLEncoder.encode(c_txt, "UTF-8");
			detailUrl = "http://m.web1234.woobi.co.kr/guest_book.php?" + 
					"mode=" + mode + "&" +
					"gb_page=" + gb_page + "&" +
					"writer=" + writer + "&" +
					"password=" + password + "&" +
					"c_txt=" + c_txt; 
		}else if(mode.equalsIgnoreCase("d")){
			String gb_id = ServletRequestUtils.getStringParameter(request, "gb_id", "");
			String gb_pwd = ServletRequestUtils.getStringParameter(request, "gb_pwd", "");
			detailUrl = "http://m.web1234.woobi.co.kr/guest_book.php?" + 
					"mode=" + mode + "&" +
					"gb_id=" + gb_id + "&" +
					"gb_pwd=" + gb_pwd; 
		}
		
		PrintWriter out = response.getWriter();
		
		Source detailSource = new Source(new URL(detailUrl));
		detailSource.fullSequentialParse();
		Element guestbook = detailSource.getElementById("guest_book");
		out.print(guestbook.toString());
	}

}
